package com.block.sms.service.quick;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.AppLoginInfo;
import com.block.sms.dto.AuthResultDTO;
import com.block.sms.service.IQuickLoginService;
import com.block.sms.utils.JiGuangUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class JiGQuickLoginServiceImpl implements IQuickLoginService {

    static Map<String, String> errorCodeMap = new HashMap<>();
    static Map<String, String> notifyCodeMap = new HashMap<>();
    static {
        errorCodeMap.put("9000", "手机号验证一致");
        errorCodeMap.put("9003", "一键登录token过期，请重新登录");
        errorCodeMap.put("9005", "请稍后登录");//同一号码连续两次提交认证间隔过短
        errorCodeMap.put("9006", "操作频繁，请明天再试");
        errorCodeMap.put("9007", "操作频繁，请明天再试");

        notifyCodeMap.put("9018", "账户余额不足");
    }

    @Override
    public ResponseVo getMobile(String outId, JSONObject tokenJson, AppLoginInfo appLoginInfo) {

        String loginToken = tokenJson.getString("loginToken");

        String auth = HttpUtil.buildBasicAuth(appLoginInfo.getApiKey(), appLoginInfo.getApiSecret(), Charset.defaultCharset());
        String contentType = "application/json";

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("loginToken", loginToken);

        String response = HttpUtil.createPost(appLoginInfo.getVerifyUrl())
                .body(JSON.toJSONString(paramMap), contentType)
                .contentType(contentType)
                .auth(auth)
                .execute()
                .body();

        log.info("【极光一键登录】请求结束【response】{}【api】{}【param】{}", response, appLoginInfo.getVerifyUrl(),  JSON.toJSONString(paramMap));

        if (response == null){
            return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "一键登录验证请求失败", "");
        }

        try {
            JSONObject jsonObject = JSONObject.parseObject(response);
            String code = jsonObject.getString("code");
            if (errorCodeMap.containsKey(code)){
                String message = errorCodeMap.get(code);
                return new ResponseVo(code, message, "");
            }

            if (notifyCodeMap.containsKey(code)){
                String message = notifyCodeMap.get(code);
                // TODO: 2021/2/27 需要邮件通知
                return new ResponseVo(code, message, "");
            }

            if (!"8000".equals(code)){
                String content = jsonObject.getString("content");
                return new ResponseVo(code, "一键登录验证失败:"+content, "");
            }

            String phoneEn = jsonObject.getString("phone");
            if (StrUtil.isEmpty(phoneEn)){
                return new ResponseVo(AppRspCodeConstant.OPERATION_FAILURE, "获取手机号失败，请尝试其他登录方式", "");
            }
            String resultPhone = JiGuangUtils.decrypt(phoneEn, appLoginInfo.getPriKey());

            AuthResultDTO resultDTO = new AuthResultDTO();
            resultDTO.setPhone(resultPhone);
            return new ResponseVo(AppRspCodeConstant.SUCCESS, resultDTO);
        }catch (Exception exception){
            log.info("【极光一键登录】解析请求结果异常【response】"+response, exception);
        }
        return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION);
    }
}
